package com.wf.smartcomm.server.listener;

import java.util.List;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.java_websocket.WebSocketImpl;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.TriggerBuilder;
import org.springframework.web.context.ContextLoaderListener;
import com.wf.smartcomm.server.job.QuartzJobFactory;
import com.wf.smartcomm.server.job.ScheduleJob;
import com.wf.smartcomm.server.service.ScheduleService;
import com.wf.smartcomm.server.service.UnitMachService;
import com.wf.smartcomm.server.util.PushUtils;
import com.wf.smartcomm.server.websocket.SmartcommServer;

public class InitializeListener implements ServletContextListener {
	
	private SmartcommServer server;
	
	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		System.out.println("contextDestroyed!!!");
		PushUtils.getApnsService().shutdown();
		Scheduler scheduler = (Scheduler) ContextLoaderListener.getCurrentWebApplicationContext().getBean("schedulerFactoryBean");
		try {
			if (scheduler.isStarted()) {
				scheduler.shutdown();
			}
			
			if (server != null) {
				server.stop();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		Scheduler scheduler = (Scheduler) ContextLoaderListener.getCurrentWebApplicationContext().getBean("schedulerFactoryBean");
		ScheduleService scheduleService = (ScheduleService) ContextLoaderListener.getCurrentWebApplicationContext().getBean("scheduleServiceImpl");
		//UnitMachService unitMachService = (UnitMachService) ContextLoaderListener.getCurrentWebApplicationContext().getBean("unitMachServiceImpl");
		List<ScheduleJob> jobs = scheduleService.list();
		for (ScheduleJob job : jobs) {
			JobDetail jobDetail = JobBuilder.newJob(QuartzJobFactory.class)
					.withIdentity(job.getJobId(), job.getJobName()).build();
			CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression());
			CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(job.getJobId(), job.getJobName())
					.withSchedule(scheduleBuilder).build();
			try {
				scheduler.scheduleJob(jobDetail, trigger);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		try {
			if (!scheduler.isStarted()) {
				scheduler.start();
			}
			/*server = new SmartcommServer(8887, unitMachService);
			server.start();
			System.out.println("scheduler and websocketServer started!!!");*/
		} catch (Exception e) {
		}
	}
}
